package com.xatl.simulated.client;

import com.xatl.simulated.constant.MqttPropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


@Slf4j
@Component
public class MqttSubscribeClient {

    @Autowired
    private MqttPropertiesUtils MqttProperties;

    @Autowired
    private MyMqttClient myMqttClient;

    private static MqttClient mqttClient = null;

    @PostConstruct
    public void init(){
        mqttClient = myMqttClient.init(MqttProperties.getSubscribe() + System.currentTimeMillis());
    }

    public static void subscribe(String topic, int qos) {
        try {
            log.info("Start to subscribe paho mqtt client!");
            mqttClient.subscribe(topic, qos);
            mqttClient.setCallback(new MqttReceiveCallback(mqttClient, topic, qos));
            log.info("Finish to subscribe paho mqtt client!");
        } catch (MqttException e) {
            log.error("Failed to subscribe paho mqtt client! Cause by {}", e.getCause());
        }
    }

}
